const { DataTypes } = require('sequelize');
const { nanoid } = require('nanoid');
const sequelize = require('../config/database');
const Customer = require('./Customer');

const MemberCard = sequelize.define('MemberCard', {
  id: {
    type: DataTypes.STRING,
    primaryKey: true,
    defaultValue: () => nanoid()
  },
  customerId: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '客户ID',
    references: {
      model: Customer,
      key: 'id'
    }
  },
  cardType: {
    type: DataTypes.ENUM('储值卡', '次卡'),
    allowNull: false,
    comment: '卡类型'
  },
  balance: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    defaultValue: 0,
    comment: '储值卡余额'
  },
  cardName: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '次卡名称'
  },
  remainingTimes: {
    type: DataTypes.INTEGER,
    allowNull: true,
    defaultValue: 0,
    comment: '剩余次数'
  },
  status: {
    type: DataTypes.ENUM('正常', '冻结', '作废'),
    allowNull: false,
    defaultValue: '正常',
    comment: '卡状态'
  }
}, {
  timestamps: true,
  paranoid: true,
  tableName: 'member_card'
});

// 建立与Customer的关联关系
MemberCard.belongsTo(Customer, {
  foreignKey: 'customerId',
  as: 'customer'
});

Customer.hasMany(MemberCard, {
  foreignKey: 'customerId',
  as: 'memberCards'
});

module.exports = MemberCard;